import axios from "axios"
import { Message } from "element-ui"

// 创建一个axios实例
const service = axios.create({
    baseURL: process.env.BASE_URL, // url = base url + request url
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem("token")
        if (token) {
            config.headers["Authorization"] = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    (response) => {
        const res = response.data
        if (response.headers.authentication) {
            localStorage.setItem("token", response.headers.authentication)
        }
        return res
    },
    (error) => {
        console.log("错误" + error) // for debug
        Message({
            message: error.message,
            type: "error",
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
